<template>
  <div class="container">
    <!-- 路径导航区域 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>师资管理</el-breadcrumb-item>
      <el-breadcrumb-item>咨询师管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索区域 -->
    <el-row>
      <el-form :inline="true">
        <el-form-item label="咨询师名称">
          <el-input v-model="queryInfo.name" clearable @clear="queryList" placeholder="请输入咨询师名称"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="queryList">搜索</el-button>
          <el-button type="success" icon="el-icon-plus" @click="toAddArticle">新增咨询师</el-button>
        </el-form-item>
      </el-form>
    </el-row>
    <!-- 表格区域 -->
    <el-table :data="consultList" border style="width: 100%" :header-cell-style="{ 'text-align': 'center' }"
      :cell-style="{ 'text-align': 'center' }">
      <el-table-column width="80px" prop="id" label="ID"></el-table-column>
      <el-table-column prop="name" label="咨询师姓名"> </el-table-column>
      <el-table-column width="80px" prop="sex" label="性别"> </el-table-column>
      <el-table-column prop="img" label="咨询师头像">
        <template slot-scope="scope">
          <el-image style="width: 100px; height: 100px" :src="url + 'downLoad?filename=' + scope.row.img"></el-image>
        </template>
      </el-table-column>
      <el-table-column prop="address" label="咨询师地址"> </el-table-column>
      <el-table-column prop="intro" label="咨询师简介"> </el-table-column>
      <el-table-column prop="book" label="证书图片">
        <template slot-scope="scope">
          <el-image style="width: 100px; height: 100px" :src="url + 'downLoad?filename=' + scope.row.book"></el-image>
        </template>
      </el-table-column>
      <el-table-column prop="levelId" label="咨询师等级" #default="scope">
        <template>
          {{ getLeverName(scope.row.levelId) }}
        </template>
      </el-table-column>
      <el-table-column prop="consultSpecialties" label="咨询师擅长领域">
        <template slot-scope="scope">
          <span v-if="
              scope.row.consultSpecialties &&
              scope.row.consultSpecialties.length
            ">
            {{
            scope.row.consultSpecialties
            .map((item) => item.specialty.name)
            .join(",")
            }}
          </span>
          <span v-else>暂无擅长领域</span>
        </template>
      </el-table-column>
      <el-table-column width="180" label="操作">
        <template slot-scope="scope">
          <el-button icon="el-icon-edit" type="primary" size="mini" @click="toEditArticle(scope.row)">编辑</el-button>
          <el-button icon="el-icon-delete" type="danger" size="mini" @click="deleteArticle(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页区域 -->
    <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
      :current-page="queryInfo.pageNum" :page-sizes="[1, 5, 10, 15, 20]" :page-size="queryInfo.pageSize"
      layout="total, sizes, prev, pager, next, jumper" :total="total">
    </el-pagination>

    <!-- 新增和修改的对话框 -->
    <el-dialog :title="title" :visible.sync="dialogFormVisible" @close="cancle">
      <el-form :model="consult">
        <el-form-item label="咨询师名称" label-width="120px">
          <el-input placeholder="请输入咨询师名称" v-model="consult.name"></el-input>
        </el-form-item>
        <el-form-item label="咨询师性别" label-width="120px">
          <el-radio v-model="consult.sex" label="男">男</el-radio>
          <el-radio v-model="consult.sex" label="女">女</el-radio>
        </el-form-item>

        <el-form-item label="咨询师头像" label-width="120px">
          <!-- el-upload:上传组件
                  action:选择图片是上传的接口
                  List-type: 上传组件的类型
                  on-success:上传成功的回调函数
                  Limit: 限制只能上传一个文件
                  on-preview:图片预览的事件
                  on-remove:删除图片的事件 -->
          <el-upload :action="url + 'upload'" list-type="picture-card" :on-success="handleSuccess" :limit="1"
            :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :file-list="fileList">
            <i class="el-icon-plus"></i>
          </el-upload>
          <!-- 预览图片 -->
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="" />
          </el-dialog>
        </el-form-item>

        <!-- 咨询师证书 -->
        <el-form-item label="咨询师证书" label-width="120px">
          <el-upload :action="url + 'upload'" list-type="picture-card" :on-success="handleSuccess2" :limit="1"
            :on-preview="handlePictureCardPreview2" :on-remove="handleRemove2" :file-list="fileList2">
            <i class="el-icon-plus"></i>
          </el-upload>
          <!-- 预览图片 -->
          <el-dialog :visible.sync="dialogVisible2">
            <img width="100%" :src="dialogImageUrl2" alt="" />
          </el-dialog>
        </el-form-item>

        <el-form-item label="咨询师地址" label-width="120px">
          <el-input placeholder="请输入咨询师地址" v-model="consult.address"></el-input>
        </el-form-item>

        <el-form-item label="咨询师等级" label-width="120px">
          <el-select v-model="consult.levelId" filterable placeholder="请选择咨询师等级">
            <el-option v-for="item in levelIdArr" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="咨询师简介" label-width="120px">
          <el-input v-model="consult.intro"></el-input>
        </el-form-item>

        <el-form-item label="咨询师擅长领域" label-width="120px">
          <el-button type="primary" @click="addSp">添加擅长领域</el-button>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancle">取 消</el-button>
        <el-button type="primary" @click="addArticle">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 擅长领域的表格 -->
    <el-dialog title="添加擅长领域" :visible.sync="dialogTableVisible">
      <el-table :data="specialtyArr" @select="handleSelectionChange" border style="width: 100%">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="id" label="ID"></el-table-column>
        <el-table-column prop="name" label="擅长领域名称"></el-table-column>
      </el-table>
      <el-button type="primary" @click="confirmSp">确认</el-button>
    </el-dialog>
  </div>
</template>
<script>
import { url } from "@/util/tools.js";
export default {
  data() {
    return {
      url: "",
      // 查询信息对象
      queryInfo: {
        name: "",
        pageNum: 1,
        pageSize: 10,
      },
      total: 183,
      consultList: [],
      title: "", // 对话框标题
      dialogFormVisible: false, // 是否显示对话框
      consult: {},
      dialogVisible: false,
      dialogVisible2: false,
      dialogImageUrl: "",
      dialogImageUrl2: "",
      fileList: [],
      fileList2: [],
      // 咨询师擅长领域
      specialtyArr: [],
      selectedRows: [], // 用来存储被选中的行
      selectedIds: [], //从行中拿到id
      // 擅长领域的表格
      dialogTableVisible: false,
      // 当前咨询师的id
      consultId: null,
      // 咨询师等级
      levelIdArr: [],
      specialtiesList: [],
    };
  },
  methods: {
    // 处理上传成功的函数
    handleSuccess(response) {
      // 把上传后的图片路径，交给文章对象的tabularChart
      this.consult.img = response.message;
    },

    // 删除图片的事件
    handleRemove(file, fileList) {
      // 移除数据
      this.consult.img = "";
    },

    // 预览图片事件
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },

    // 处理上传成功的函数
    handleSuccess2(response) {
      // 把上传后的图片路径，交给文章对象的tabularChart
      this.consult.book = response.message;
    },

    // 删除图片的事件
    handleRemove2(file, fileList) {
      // 移除数据
      this.consult.book = "";
    },

    // 预览图片事件
    handlePictureCardPreview2(file) {
      this.dialogImageUrl2 = file.url;
      this.dialogVisible2 = true;
    },

    // 删除文章
    deleteArticle(id) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$http.delete("consult/" + id).then((resp) => {
            if (resp.data.status == 200) {
              this.$message.success(resp.data.message);
              this.queryList();
            } else {
              this.$message.error(resp.data.message);
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 进入添加的对话框
    toAddArticle() {
      this.title = "新增咨询师";
      this.dialogFormVisible = true;
    },
    // 进入修改的预览数据页面
    toEditArticle(row) {
      // console.log(row)
      // 赋值
      this.consult = row;
      console.log(row);
      this.consultId = row.id;

      // 设置标题
      this.title = "修改咨询师信息";
      // 开启对话框
      this.dialogFormVisible = true;
      // 动态的获取图片的名称并帮到到fileList
      this.fileList = [
        {
          name: row.img,
          url: url + "downLoad?filename=" + row.img,
        },
      ];
      this.fileList2 = [
        {
          name: row.book,
          url: url + "downLoad?filename=" + row.book,
        },
      ];
    },
    // 添加咨询师
    addArticle() {
      console.log(this.consult.id);
      if (this.consult.id) {
        // 有值为true  修改
        this.$http.put("consult/edit", this.consult).then((resp) => {
          if (resp.data.status == 200) {
            // 消息提示
            this.$message.success("修改成功！");
            // 清空数据
            (this.consult = {
              // 咨询师对象
              id: "",
              name: "",
              sex: "",
              img: "",
              address: "",
              intro: "",
              book: "",
              // specialties: [],
            }),
              // 关闭对话框
              (this.dialogFormVisible = false);
            // 重新查询
            this.queryList();
          } else {
            this.$message.error("接口异常！");
          }
        });
      } else {
        this.$http.post("consult/add", this.consult).then((resp) => {
          if (resp.data.status == 200) {
            // 消息提示
            this.$message.success("添加成功！");
            // 清空数据
            this.consult = {
              // 咨询师对象
              id: "",
              name: "",
              sex: "",
              img: "",
              address: "",
              intro: "",
              book: "",
              specialties: [],
            };
            // 关闭对话框
            this.dialogFormVisible = false;
            // 重新查询
            this.queryList();
          } else {
            this.$message.error("接口异常！");
          }
        });
      }
      //  在取消函数，添加成功， 修改成功的函数中加入以下代码实现图片的清空
      this.fileList = [];
      this.fileList2 = [];
    },
    cancle() {
      this.dialogFormVisible = false;
      this.consult = {
        id: "",
        name: "",
        sex: "",
        img: "",
        address: "",
        intro: "",
        book: "",
        specialties: [],
      };
      //  在取消函数，添加成功， 修改成功的函数中加入以下代码实现图片的清空
      this.fileList = [];
      this.fileList2 = [];
    },
    queryList() {
      this.$http
        .get("consult/findByPage", {
          params: this.queryInfo,
        })
        .then((res) => {
          if (res.data.status == 200) {
            this.consultList = res.data.data.list;
            this.total = res.data.data.total;
            this.specialtiesList = res.data.data.list.map(
              (item) => item.consultSpecialties
            );
            console.log(this.specialtiesList);
          } else {
            this.$message.error("查询失败!");
          }
        });
    },
    // 获取咨询师擅长领域的所有
    specialtyAll() {
      this.$http.get("/specialty/findByPage").then((res) => {
        if (res.data.status == 200) {
          this.specialtyArr = res.data.data.list;
        }
        console.log("擅长领域的所有", this.specialtyArr);
      });
    },

    // 获取咨询师等级的所有
    consultleverAll() {
      this.$http.get("/consultlever/findByPage").then((res) => {
        if (res.data.status == 200) {
          this.levelIdArr = res.data.data.list;
        }
      });
    },
    handleSizeChange(size) {
      this.queryInfo.pageSize = size;
      this.queryInfo.pageNum = 1;
      console.log("每页显示数量发生改变", this.queryInfo.pageSize);
      this.queryList();
      console.log("数据", this.consultList);
    },
    handleCurrentChange(num) {
      // console.log('页码发生改变');
      this.queryInfo.pageNum = num;
      this.queryList();
    },
    getLeverName(leverId) {
      // console.log(leverId);
      for (let i = 0; i < this.levelIdArr.length; i++) {
        if (this.levelIdArr[i].id == leverId) {
          return this.levelIdArr[i].name;
        }
      }
    },
    // 添加擅长领域
    addSp() {
      this.dialogTableVisible = true;
      this.dialogFormVisible = false;
      // 获取当前咨询师的id
      console.log("当前咨询师的id为" + this.consultId);
    },
    handleSelectionChange(val) {
      this.selectedRows = val;
    },
    confirmSp() {
      if (this.selectedRows.length > 0) {
        console.log("被选中的数据:", this.selectedRows);
        this.selectedIds = this.selectedRows.map((item) => item.id);
        // console.log(this.selectedIds);
        let specialtyIds = JSON.parse(JSON.stringify(this.selectedIds));
        console.log(specialtyIds);

        this.$http
          .post("/consultspecialty/updateSpecialty", {
            consultId: this.consultId,
            specialtyIds: specialtyIds,
          })
          .then((res) => {
            if (res.data.status == 200) {
              // 添加成功后关闭弹窗
              this.dialogTableVisible = false;
              this.queryList();
            }
          });
      }
    },
  },

  mounted() {
    this.specialtyAll();
    this.consultleverAll();
    // 动态的获取tool.js中的url，并赋值给当前组件的全局url
    this.url = url;
    this.queryList();
  },
};
</script>
<style>
.el-breadcrumb {
  margin-bottom: 15px;
  padding: 0 0 15px;
  border-bottom: 1px solid #ddd;
}

.el-pagination {
  margin-top: 15px;
}

.el-link {
  padding: 0 5px;
}

/**设置富文本编辑器的最小高度，注意style中不能使用scoped **/
.ql-container {
  min-height: 200px;
}
</style>